<template>
  <a-modal title-align="start" title="提交仓库" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1200">
    <a-table :data="tableData" size="mini" :pagination="false" :scroll="{ x: '100%', y: '400px' }" class="table-two-line mt10">
      <template #columns>
        <a-table-column title="图片" #cell="{ record }" :width="50">
          <a-image @click="showBigImg(record)" :preview="false" :src="$extract(props.getPicList(record)[0], 'url')" width="40" height="40" />
        </a-table-column>
        <a-table-column title="产品SKU" #cell="{ record }" :width="120">
          {{ $extract(record, 'product.productSku') }}
        </a-table-column>
        <a-table-column title="销售公司/销售员" #cell="{ record }" :width="140">
          <div>{{ record.companyName }}</div>
          <div>{{ $extract(record, 'saler.name') }}</div>
        </a-table-column>
        <a-table-column title="定制编号" #cell="{ record }" :width="100">
          {{ record.customCode }}
        </a-table-column>
        <a-table-column title="数量" #cell="{ record }" :width="60">
          {{ record.qtyPurchase }}
        </a-table-column>
        <a-table-column title="定制类型" #cell="{ record }" :width="80">
          {{ $extract(record, 'customInfo.customType') }}
        </a-table-column>
        <a-table-column title="材质" #cell="{ record }" :width="60">
          {{ $extract(record, 'customInfo.material') }}
        </a-table-column>
        <a-table-column title="材质单价（元/g）" #cell="{ record }" :width="80">
          {{ $extract(record, 'saleCloesCost.amtAvgMaterial') }}
        </a-table-column>
        <a-table-column :width="100">
          <template #title>
            <a-popover content="采购成本是指该单需要支付给供应商的费用，就是供应商交货时的合计金额">
              <p>
                <span class="required">采购成本</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }"> {{ $extract(record, 'supplierCloseCost.amtTotal') }}</template>
        </a-table-column>
        <a-table-column :width="100">
          <template #title>
            <a-popover content="材质净重是指产品出库时扣除石头和链条之外的重量。默认取供应商交货时填写的净重量">
              <p>
                <span class="required">材质净重</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'saleCloesCost.wgtNetMaterial') || '0' }}</template>
        </a-table-column>

        <a-table-column :width="120">
          <template #title>
            <a-popover content="连耗重量，是指净重加上损耗的重量。默认取供应商交货时填写的连耗重量">
              <p>
                <span class="required">连耗重量(g)</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'saleCloesCost.wgtContinueAttrition') }}</template>
        </a-table-column>

        <a-table-column :width="140">
          <template #title>
            <a-popover>
              <p>
                <span class="required">半成品毛坯供应方</span>
                <icon-question-circle />
              </p>
              <template #content>
                <div>供应商：表示该单提交工厂时选择了无需领料，半成品是由供应商提供的。</div>
                <div>采购方：表示该单提交工厂时选择了采购部的仓库领料，半成品是由采购部提供的。</div>
                <div>需求方：表示该单提交工厂时选择了“番禺半成品仓”领料，半成品是由销售自己提供的。</div>
              </template>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            {{ record.saleCloesCost.semiNoPick ? '供应商' : record.saleCloesCost.semiWarehouseName }}
          </template>
        </a-table-column>

        <a-table-column :width="100">
          <template #title>
            <a-popover>
              <p>
                <span class="required">半成品货值</span>
                <icon-question-circle />
              </p>
              <template #content>
                <div>半成品货值是指半成品毛坯的成本。</div>
                <div>默认值来源</div>
                <div>半成品供应方=供应商：材质单价*连耗重量</div>
                <div>半成品供应方=采购方：半成品出库时的库存单价*数量</div>
                <div>半成品供应方=需求方：半成品出库时的库存单价*数量</div>
              </template>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ $extract(record, 'saleCloesCost.amtAvgSemiStock') }}</template>
        </a-table-column>

        <a-table-column :width="160">
          <template #title>
            <a-popover content="采购工费是指业务部门需要支付给采购部门的跟单服务费，默认取工费报价，没有则取该产品上一个单子的工费">
              <p>
                <span class="required">采购工费</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @input="getAmount(record)" v-model="record.saleCloesCost.amtPurchaseLabor" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtPurchaseLabor')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>

        <a-table-column :width="160">
          <template #title>
            <a-popover content="如果该单的石头是由采购部门或者是供应商提供的则在此输入石头的成本">
              <p>
                <span class="required">石头费用</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @input="getAmount(record)" v-model="record.saleCloesCost.amtStone" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtStone')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>

        <a-table-column :width="160">
          <template #title>
            <a-popover content="如果该单的链条是由采购部门或者供应商提供的则在此输入链条的成本">
              <p>
                <span class="required">链条费用</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @input="getAmount(record)" v-model="record.saleCloesCost.amtChain" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtChain')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>

        <a-table-column :width="160" title="其他费用">
          <template #cell="{ record, rowIndex }">
            <a-space>
              <a-input placeholder="请输入" @input="getAmount(record)" v-model="record.saleCloesCost.amtOther" />
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'amtOther')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>

        <a-table-column :width="100">
          <template #title>
            <a-popover>
              <p>
                <span class="required">合计金额</span>
                <icon-question-circle />
              </p>

              <template #content>
                <div>这里的合计金额，是指业务部门需要支付给采购部门的总费用，所以需要根据半产品供应方是谁分开计算。</div>
                <div>半成品供应方=供应商：半成品货值+采购工费+石头费用+链条费用+其他费用</div>
                <div>半成品供应方=采购方：半成品货值+采购工费+石头费用+链条费用+其他费用</div>
                <div>半成品供应方=需求方：采购工费+石头费用+链条费用+其他费用</div>
              </template>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ record.saleCloesCost.amtTotal ? record.saleCloesCost.amtTotal : '--' }}</template>
        </a-table-column>
        <a-table-column :width="220">
          <template #title>
            <a-popover content="默认取供应商交货是填写的税率">
              <p>
                <span class="required">税率</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">
            <a-space>
              <div class="flex">
                <a-select style="width: 90px" @change="getAmount(record)" v-model="record.saleCloesCost.includeTax">
                  <a-option :value="true">含税</a-option>
                  <a-option :value="0">不含税</a-option>
                </a-select>
                <a-select style="width: 80px" @change="getAmount(record)" v-model="record.saleCloesCost.taxRate">
                  <a-option :value="3">3%</a-option>
                  <a-option :value="13">13%</a-option>
                </a-select>
              </div>
              <a-button size="small" class="gray-outline" @click="setGloableDate(rowIndex, record, 'includeTax')">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>

        <a-table-column :width="80">
          <template #title>
            <a-popover content="税金=合计金额*税率">
              <p>
                <span class="required">税金</span>
                <icon-question-circle />
              </p>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ record.saleCloesCost.amtTax ? record.saleCloesCost.amtTax : '--' }}</template>
        </a-table-column>
        <a-table-column :width="80">
          <template #title>
            <a-popover content="连耗重量，是指净重加上损耗的重量。默认取供应商交货时填写的连耗重量">
              <p>
                <span class="required">货值</span>
                <icon-question-circle />
              </p>

              <template #content>
                <div>含税货值=（半成品货值+采购工费+石头费用+链条费用+其他费用）-税金</div>
                <div>不含税货值=半成品货值+采购工费+石头费用+链条费用+其他费用</div>
              </template>
            </a-popover>
          </template>
          <template #cell="{ record, rowIndex }">{{ record.saleCloesCost.amtGoodValue ? record.saleCloesCost.amtGoodValue : '--' }}</template>
        </a-table-column>

        <a-table-column :width="60" title="操作" #cell="{ rowIndex }" fixed="right">
          <a-button type="text" style="color: red" @click="tableData.splice(rowIndex, 1)">移除 </a-button>
        </a-table-column>
      </template>
    </a-table>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>

  <a-image-preview-group v-model:visible="visible" infinite :srcList="srcList" />
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { batchPurchaseSumitWarehouse, listLatestCustomOrderPurchase } from '@/api/purchase'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'list', 'getPicList'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  let tableData = ref<Array<any>>([])
  let srcList = ref([])
  let visible = ref(false)
  let tableLoading = ref(false)
  let submitLoading = ref(false)
  const init = async () => {
    props.list.forEach((e: any) => {
      let obj = _.cloneDeep(e)

      obj.warehouseCompany = {
        companyId: 'P493',
        companyName: '雅菲妮云仓',
      }

      obj.saleCloesCost = obj.supplierCloseCost || {}
      obj.saleCloesCost.amtTotal = ''
      obj.saleCloesCost.amtGoodValue = ''
      obj.saleCloesCost.amtTax = ''
      obj.saleCloesCost.amtPurchaseCost = obj.supplierCloseCost.amtTotal
      obj.saleCloesCost.amtSemiGoodValue = obj.supplierCloseCost.amtAvgSemiStock

      tableData.value.push(obj)
    })

    await getPurchasePrice()

    tableData.value.forEach((e: any) => {
      getAmount(e)
    })
  }

  const showBigImg = (item: any) => {
    let arr = props.getPicList(item)
    srcList.value = arr.map((e: any) => e.url)
    visible.value = true
  }

  const submit = async () => {
    try {
      let params = {
        list: tableData.value,
      }
      submitLoading.value = true
      const res: any = await batchPurchaseSumitWarehouse(params)
      if (res) {
        Message.success('提交成功')
        showvisible.value = false
        emits('save')
      }
    } catch (error) {}
    submitLoading.value = false
  }

  function formatFloatToFourDecimalPlaces(num: any) {
    // 将数字转换为字符串
    let numStr = num.toString()

    // 检查是否包含小数点
    if (numStr.includes('.')) {
      // 如果包含小数点，则使用 toFixed 保留四位小数
      return parseFloat(num.toFixed(4)).toString()
    } else {
      // 如果不包含小数点（即整数），则直接返回原字符串
      return numStr
    }
  }

  const getAmount = (data: any) => {
    let num1 = Number(data.saleCloesCost.amtPurchaseLabor) || 0
    let num2 = Number(data.saleCloesCost.amtStone) || 0
    let num3 = Number(data.saleCloesCost.amtChain) || 0
    let num4 = Number(data.saleCloesCost.amtOther) || 0
    let num5 = Number(data.saleCloesCost.amtAvgSemiStock) || 0
    if (!data.supplierCloseCost.semiNoPick && data.supplierCloseCost.semiWarehouseCode == 'CK86') {
      data.saleCloesCost.amtTotal = num1 + num2 + num3 + num4
    } else {
      data.saleCloesCost.amtTotal = num1 + num2 + num3 + num4 + num5
    }

    data.saleCloesCost.amtTax = formatFloatToFourDecimalPlaces(data.saleCloesCost.amtTotal * (data.saleCloesCost.taxRate / 100))

    if (data.supplierCloseCost.includeTax) {
      data.saleCloesCost.amtGoodValue = data.saleCloesCost.amtTotal ? data.saleCloesCost.amtTotal - Number(data.saleCloesCost.amtTax) : 0
    } else {
      data.saleCloesCost.amtGoodValue = data.saleCloesCost.amtTotal > 0 ? data.saleCloesCost.amtTotal : 0
    }
  }

  const setGloableDate = (index: number, data: any, type: string) => {
    tableData.value.forEach((e: any, i: number) => {
      if (i > index) {
        if (type == 'includeTax') {
          e.saleCloesCost.taxRate = data.saleCloesCost.taxRate
        } else {
          e.saleCloesCost[type] = data.saleCloesCost[type]
        }
        getAmount(e)
      }
    })
  }

  // 单次加工费
  const getPurchasePrice = async () => {
    let params: any = {
      list: [],
    }
    tableData.value.forEach((e: any) => {
      let obj = {
        companyId: e.companyId,
        productSku: e.product.productSku,
        status: '130',
      }
      params.list.push(obj)
    })
    const res: any = await listLatestCustomOrderPurchase(params)

    let arr = res?.data
    tableData.value.forEach((e: any, i: number) => {
      if (!e.saleCloesCost) {
        e.saleCloesCost = {
          amtPurchaseLabor: arr[i].latest?.saleCloesCost?.amtPurchaseLabor || '',
        }
      } else {
        e.saleCloesCost.amtPurchaseLabor = arr[i].latest?.saleCloesCost?.amtPurchaseLabor || ''
      }
    })
  }

  onMounted(async () => {
    init()
  })
</script>

<style lang="less" scoped></style>
